package com.guet.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.guet.utils.RedisConstants.*;

@Component
public class RedisUtils {
    private final StringRedisTemplate stringRedisTemplate;
    // 执行缓存重建的线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public RedisUtils(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透,存空值
     * @param dbFallback 查询数据库的逻辑
     * @param <R> 返回数据的类型
     * @param <ID> id的类型可能是Long,也可能是字符串
     */
    public <R,ID> R queryWithPassThrough
            (String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,Long time,TimeUnit unit){
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json,type);
        }
        if(json != null){
            return null;
        }

        R r = dbFallback.apply(id);
        if(r == null){
            stringRedisTemplate.opsForValue().set(keyPrefix + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        set(keyPrefix + id,r,time,unit);
        return r;
    }

    /**
     * 使用逻辑过期解决 缓存击穿
     * 针对热点key问题(提前加载好,且不会实际设置过期时间)
     * 所以不考虑缓存穿透,缓存中没有就是没有了
     */
    public <R,ID> R queryWithLogicalExpire
            (String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,Long time,TimeUnit unit){
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        // 缓存中没有就是没有了
        if(StrUtil.isBlank(json)){
            return null;
        }
        // 命中
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        // 数据过期,新开线程执行缓存重建
        if(getLock(LOCK_SHOP_KEY + id)){
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r1 = dbFallback.apply(id);
                    setWithLogicalExpire(keyPrefix + id,r1,time,unit);
                }catch(Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unlock(LOCK_SHOP_KEY + id);
                }
            });
        }
        // 返回过期的数据或新的数据
        return r;
    }
    private boolean getLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
